var express = require('express');
var md5 = require("md5");
var router = express.Router();
var userDAO = require("../bin/db/userDAO.js");
var ccap = require("ccap");
var fs = require("fs");

var captcha = ccap({
 	width:160,
	height:40,
	quality:30,
	fontsize:40,
	generate:function(){
        var sourceStr = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        var text = "";
        for(var i = 0;i<4;i++){
            var index = Math.floor(Math.random()*sourceStr.length);
            var ch = sourceStr[index];
            text+=ch;
        }
        return text;
	}

});
router.get("/captcha",(req,res)=>{
    var arr = captcha.get();
    req.session.captcha = arr[0];
    res.set("Content-Type","image/jpeg");
    res.send(arr[1]);
});

// 注册接口
router.post("/regist",(req,res)=>{
    if(req.body.captcha.toUpperCase()!=req.session.captcha){
        res.json({err:1,msg:"验证码错误"});
        return;
    }
    var reg = /^\w{3,12}$/;
    if(!reg.test(req.body.account)){
        res.json({err:1,msg:"账号格式错误"});
        return;
    }
    var reg = /^\d{6}$/;
    if(!reg.test(req.body.psw)){
        res.json({err:1,msg:"密码格式错误"});
        return;
    }
    if(req.body.psw!=req.body.confirm){
        res.json({err:2,msg:"两次密码输入不一致，请重新输入"});
        return;
    }
    userDAO.findOne({account:req.body.account})
    .then(function(data){
        if(data){
            res.json({err:1,msg:"此账号已占用"});
        }else{
            req.body.psw = md5(req.body.psw);
            var n = new userDAO({
                account:req.body.account,
                psw:req.body.psw,
            });
            n.save(function(err){
                res.json({err:0,msg:"注册成功"});
            })
        }
    }) 
});

// 登录接口
router.post("/login",(req,res)=>{
    if(req.body.captcha){
        if(req.body.captcha.toUpperCase()!=req.session.captcha){
            res.json({err:1,msg:"验证码错误"});
            return;
        }
        userDAO.findOne({account:req.body.account})
        .then(data=>{
            if(!data){
                var n = new userDAO({
                account:req.body.account,
                psw:md5(req.body.psw),
                });
                n.save(function(){
                    req.body.psw = md5(req.body.psw);
                    userDAO.findOne({account:req.body.account,psw:req.body.psw})
                    .then(data=>{
                        if(!data){
                            res.json({err:1,msg:"账号或密码错误"});
                        }else{
                            req.session.user = data;
                            res.json({err:0,msg:"登录成功"});
                        }
        });
                });
            }else{
                req.session.user = data;
                res.json({err:0,msg:"登录成功"});
            }
        });
           
    }else{
          req.body.psw = md5(req.body.psw);
            userDAO.findOne({account:req.body.account,psw:req.body.psw})
            .then(data=>{
                if(!data){
                    res.json({err:1,msg:"账号或密码错误"});
                }else{
                    req.session.user = data;
                    res.json({err:0,msg:"登录成功"});
                }
        });
    }
      
});

// 判断是否登录

router.get("/isLogin",function(req,res){
    var isLogin = false;
    if(req.session.user){
        isLogin = true;
        var userinfo = req.session.user
        var param = {
            isLogin:isLogin,
            userinfo:userinfo
        }
        res.json({err:0,param:param});
    }else{
        res.json({err:0,isLogin:isLogin});
    }
});

// 退出登录

router.get("/logout",(req,res)=>{
    if(req.session.user){
        req.session.user="";
    }
    res.json({err:0,msg:"退出成功"});
});

// 头像上传

var multer = require("multer");
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/images/avatar');
    },
    filename: function (req, file, cb) {
         if(!req.pic){
            req.pic = "";
        }
        var time = Date.now();
        var suffix = file.mimetype.split("/")[1];
        var fn = time+"."+suffix;
        req.pic=fn;
        cb(null,fn);
    }
});
var upload = multer({storage:storage});

//头像上传接口
router.post("/upload",function(req,res,next){
    if(!req.session.user){
        res.json({err:0,msg:"请先登录"});
    }else{
        next();
    }
});
router.post("/upload",upload.single("avatar"),function(req,res){
    userDAO.findOne({_id:req.session.user._id},function(err,data){
         
         data.avatar = req.pic;
        data.save(function(err){
            res.json({msg:"上传成功"});
        });
    });
});

// 查询头像接口
router.post("/searchavatar",(req,res)=>{
    userDAO.findOne({_id:req.body._id})
    .then(data=>{
        res.json({err:0,data:data});
    })
})

module.exports = router;
